﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Vaffanculo.Presentation.Component.WizardControl
{
    /// <summary>
    /// Interaction logic for PageProgress.xaml
    /// </summary>
    public partial class PageProgress : System.Windows.Controls.UserControl, IPageProcessComponent
    {
        private readonly List<ProceedureCompleteDelegate> _proceedureCompleteDelegates = new List<ProceedureCompleteDelegate>();
        private int _counter;
        private delegate void RefreshDelegate();
        private Thread _t;

        public PageProgress()
        {
            InitializeComponent();
        }

        public string KeyText
        {
            get { return "Progreso"; }
        }

        public List<ProceedureCompleteDelegate> ProceedureCompleteDelegates
        {
            get { return _proceedureCompleteDelegates; }
        }

        public void StartProceedure()
        {
            _t = new Thread(UpdateProgressLoop) {Name = "Default Master Progress Thread"};
            _t.Start();
        }

        public bool CancelProceedure()
        {
            try
            {
                Thread.Sleep(2000);
            }
            catch (Exception)
            {
            }

            try
            {
                _t.Abort();

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        private void UpdateProgressLoop()
        {
            try
            {
                while (_counter < 100)
                {
                    _counter++;

                    Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new RefreshDelegate(UpdateProgress));

                    try
                    {
                        Thread.Sleep(500);
                    }
                    catch (Exception)
                    {
                    }
                }

                _counter = 100;
                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new RefreshDelegate(UpdateProgress));

                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new RefreshDelegate(UpdateFinished));
            }
            catch (Exception)
            {
                Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new RefreshDelegate(UpdateFinished));
            }
        }

        private void UpdateProgress()
        {
            progressBar.Value = _counter;
        }

        private void UpdateFinished()
        {
            foreach (ProceedureCompleteDelegate t1 in _proceedureCompleteDelegates)
            {
                t1.Invoke();
            }
        }
    }
}
